package branch;

import fileoperation.FileCreation;
import fileoperation.FileDeletion;
import repository.Repository;

import java.io.*;
import java.util.Arrays;
import java.util.List;

public class Branch {
    public String branchName = "master"; //当前分支，默认为master
    public String commitKey; //当前分支指向的commit
    public static String branchPath = Repository.getGitDir() + File.separator + "refs" + File.separator + "heads";
    public Branch(){}

    public static String getBranchName() throws IOException {
        FileInputStream is = new FileInputStream(Repository.getGitDir() + File.separator + "HEAD");
        BufferedReader br=new BufferedReader(new InputStreamReader(is));
        String refsPath=br.readLine();//读取HEAD文件内容
        List<String> branchList = Arrays.asList(refsPath.split("/"));//按照斜杠分割分支路径得到分支名
        String branchname = branchList.get(branchList.size() - 1);
        return branchname;
    }

    public String getCommitKey() throws IOException {
        String headPath = branchPath + File.separator + branchName;
        FileInputStream is = new FileInputStream(headPath);
        BufferedReader br=new BufferedReader(new InputStreamReader(is));
        commitKey=br.readLine();//读取heads文件内容
        return commitKey;
    }


    public static void modifyBranch(String commitKey) throws IOException {

        File branchFile = new File(branchPath + File.separator + getBranchName());
        FileWriter fileWriter = new FileWriter(branchFile);//在分支文件中记录当前commit
        fileWriter.write(commitKey);
        fileWriter.close();
    }

    public void creatBranch(String name) throws IOException {
        File file = new File(branchPath + File.separator + name);
        if(file.exists()){
            FileDeletion.deleteFile(file);//分支已经存在，重置该分支
        }
        FileCreation.createFile(branchPath, name, getCommitKey());//分支不存在则创建分支
        FileWriter fileWriter = new FileWriter(file);//在分支文件中记录当前commit
        fileWriter.write(commitKey);
        fileWriter.close();
    }

}